package user

import (
	"context"
	"github.com/golang-jwt/jwt/v4"
	"go-zero-project/common/ctxdata"
	"go-zero-project/common/excption"
	tools "go-zero-project/common/utils"
	"go-zero-project/services/user/rpc/constans"
	"time"

	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGenerateTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateTokenLogic {
	return &GenerateTokenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GenerateTokenLogic) GenerateToken(in *pb.GenerateTokenReq) (*pb.GenerateTokenResp, error) {
	// 获取当前事件
	nowTime := time.Now().Unix()
	// 获取配置的过期时间
	accessExpire := l.svcCtx.Config.JwtAuth.AccessExpire
	jwtToken, err := l.getJwtToken(l.svcCtx.Config.JwtAuth.AccessSecret, nowTime, accessExpire, in.UserId)
	if err != nil {
		logx.Errorf("创建token失败,请求参数：{}", tools.BeanToJson(in), err)
		return nil, excption.NewErrCode(constans.CreateTokenError)
	}

	return &pb.GenerateTokenResp{
		AccessToken:  jwtToken,
		AccessExpire: nowTime + accessExpire,
		RefreshAfter: nowTime + accessExpire/2,
	}, nil
}

func (l *GenerateTokenLogic) getJwtToken(secret string, nowTime int64, expire int64, userId int64) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = nowTime + expire
	claims["iat"] = nowTime
	claims[ctxdata.CtxKeyJwtUserId] = userId
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(secret))
}
